package middleware

import (
	"grpc.getaway.adminspro.padmins.com/internal/api/module/admin/container"
	"grpc.getaway.adminspro.padmins.com/pkg/config/businessError"
)

const (
	levelPublic = 1
	levelAllow  = 2
)

var routersPermission = map[string]int{
	"auth.login":               levelPublic,
	"auth.getPicCaptchaConfig": levelPublic,
	"auth.logout":              levelPublic,
	"auth.getInfo":             levelAllow,
}

func PermissionMiddleware(c *container.Context) bool {
	token := c.Request.Header("Access-Token")
	resource := c.Request.ParamsToString("method")

	if resource == "" {
		c.Write(c.ResponseMessage.JSON(businessError.MethodEmpty.Code, businessError.MethodEmpty.Msg, nil))
		return false
	}

	permission := routersPermission[resource]

	if token == "" {
		token = c.Request.Header("Authorization")
	}

	if token == "" {
		token = c.Request.Cookie("token")
	}

	if token == "" {
		token = c.Request.ParamsToString("token", "")
	}

	b, e := c.Auth.Init(c.GetContext(), token, resource)

	if e != nil {
		c.Write(c.ResponseMessage.JSON(e.Code, e.Msg, nil))
		return false
	}

	if b == false {
		if permission == levelPublic {
			return true
		}
		c.Write(c.ResponseMessage.JSON(businessError.AuthTokenInvalid.Code, businessError.AuthTokenInvalid.Msg, nil))
		return false
	}

	if c.Auth.Data.Admin.Status != 1 {
		c.Write(c.ResponseMessage.JSON(businessError.AuthAdminForbidden.Code, businessError.AuthAdminForbidden.Msg, nil))
		return false
	}

	if permission == levelAllow || permission == levelPublic {
		c.Auth.SetAllowResources([]interface{}{
			resource,
		})
	}

	if c.Auth.Permission() == false {
		c.Write(c.ResponseMessage.JSON(businessError.AuthDeniedPermission.Code, businessError.AuthDeniedPermission.Msg, nil))
		return false
	}

	return true
}
